<template>
  <div>
    <van-field
      v-model="curValue"
      :name="config.code"
      :label="config.aliasName"
      :placeholder="`请选择${config.aliasName}`"
      :disabled="config.disabled"
      readonly
      @click="handlerShowPicker"
      :rules="[
        {
          required: config.isMust,
          trigger: 'onChange',
          message: `请正确的选择${config.aliasName}`,
        },
      ]"
    />

    <van-popup v-model="showPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="options"
        @cancel="showPicker = false"
        @confirm="onConfirmPicker"
      />
    </van-popup>
  </div>
</template>

<script>
import { Picker, Popup, Field } from "vant";

export default {
  name: "FormSelect",
  components: {
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [Field.name]: Field,
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    config: {
      type: Object,
      default: {},
    },
  },
  watch: {
    value: {
      handler(val) {
        if(!val){
          return;
        }
        const obj = this.config.selectMap; // 转换成对应的value赋值，而不是key
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            const ele = obj[key];
            if (key === val) {
              this.curValue = ele;
            }
          }
        }
        // this.curValue = val;
      },
      immediate: true,
    },
    curValue(val) {
      const obj = this.config.selectMap; // 取出key给外部，而不是value
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          const ele = obj[key];
          if (ele === val) {
            val = key;
          }
        }
      }
      this.$emit("input", val);
    },
  },
  computed: {
    options() {
      const obj = this.config.selectMap;
      const arr = [];
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          const ele = obj[key];
          arr.push(ele);
        }
      }
      return arr;
    },
  },
  data() {
    return {
      curValue: undefined,
      showPicker: false,
    };
  },
  methods: {
    handlerShowPicker() {
      if (!this.config.disabled) {
        this.showPicker = true;
      }
    },
    onConfirmPicker(val) {
      this.curValue = val;
      this.showPicker = false;
    },
  },
};
</script>
